package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.entity.UserInfo;
import com.hmdp.mapper.UserInfoMapper;
import com.hmdp.service.IUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-24
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private IUserService userService;

    /*点击发送手机验证码执行这个方法*/
    @Override
    public Result sendCode(String phone, HttpSession session) {
        /*1.判断手机号是否为空或则无效*/
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式错误");
        }
        /*2.手机号不为空，生成验证码，向手机号里面发送验证码*/
        String code = RandomUtil.randomNumbers(6);
        /*像手机里面发送验证码*/
        log.debug("发送的验证码是："+code);
        /*3.将验证码放入到redis里面，设置过期时间*/
        redisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY+phone, code, RedisConstants.LOGIN_CODE_TTL,TimeUnit.MINUTES);
        return Result.ok();
    }

    /*点击登录按钮就执行这个方法*/
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        /*判断code是否为空，是否符合规则*/
        String code = loginForm.getCode();
        if(RegexUtils.isCodeInvalid(code)){
            return Result.fail("验证码格式错误，请重新输入");
        }
        if(RegexUtils.isPhoneInvalid(loginForm.getPhone())){
            return Result.fail("请检查手机号是否填写正确");
        }
        /*判断验证码是否填写正确*/
        String RedisCode = redisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + loginForm.getPhone());
        if(RedisCode==null || !RedisCode.equals(loginForm.getCode())){
            return Result.fail("验证码填写错误！");
        }
        /*查询该手机号在数据库里面是否存在*/
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", loginForm.getPhone());
        User user = userService.getOne(wrapper);
        if(user==null){
            /*创建一个用户*/
            user = createUser(loginForm);
        }
        /*保存用户到redis里面*/
        /*为true表示不带下划线的字符串*/
        String token= UUID.randomUUID().toString(true);
        String tokenKey=RedisConstants.LOGIN_USER_KEY+token;
        /*将user对象转换为hashmap存储*/
        /*这里要转换成userDTO，为了保护用户隐私*/
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        /*将userDTO转换成map,在转换的时候，对转换过程的时候进行说明*/
//        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        /*将信息存入redis,设置redis的过期时间*/
        redisTemplate.opsForHash().putAll(tokenKey, userMap);
        redisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);
        /*返回的是一个token字符串，*/
        System.out.println("token是:"+token);
        return Result.ok(token);
    }


    /*创建一个用户*/
    private User createUser(LoginFormDTO loginForm) {
        User user = new User();
        user.setPhone(loginForm.getPhone());
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX+RandomUtil.randomString(10));
        userService.save(user);
        return user;
    }


}
